/*
* 路由
*
*/
import Vue from 'vue';
import Router from 'vue-router';
import componentConfig from '@/utils/config.view.router';

// 处理升级后的路由跳转报Uncaught (in promise)问题
const originalPush = Router.prototype.push;
Router.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject);
  return originalPush.call(this, location).catch(err => err);
};
Vue.use(Router);

// 自动适应modules下的路由
const req = require.context('./modules', true, /\.js$/);
var RoutermModules = [];
var reg = /.\/(.*).js/;
req.keys().map((item, index) => {
  var name = reg.exec(item)[1];
  RoutermModules[index] = require('./modules/' + name + '.js').default;
});
export const constantRouterMap = [{
  name: 'login',
  path: '/login',
  meta: {
    keepAlive: true // 缓存
  },
  component: componentConfig.login
}, {
  name: 'register',
  path: '/register',
  hidden: true,
  meta: {
    keepAlive: true // 缓存
  },
  component: componentConfig.register
}, {
  name: 'layout',
  path: '/',
  component: componentConfig.layout,
  redirect: '/home',
  children: RoutermModules
}, {
  name: '404',
  path: '/error',
  component: componentConfig.error
}, {
  name: 'default',
  path: '*',
  redirect: '/error'
}];

const router = new Router({
  mode: 'history', // 后端支持可开
  scrollBehavior: (to, from, savedPosition) => {
    // keep-alive 返回缓存页面后记录浏览位置
    if (savedPosition && to.meta.keepAlive) {
      return savedPosition;
    }
    // 异步滚动操作
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve({ x: 0, y: 1 });
      }, 0);
    });
  },
  routes: constantRouterMap
});
export default router;
